<template>
  <div>
    <div class="card" style="padding: 15px">
      您好，{{ user?.name }}！欢迎使用本系统
    </div>

    <div style="display: flex; margin: 10px 0">
      <div style="width: 50%;" class="card">
        <div style="margin-bottom: 30px; font-size: 20px; font-weight: bold">赛事通知</div>
        <div>
          <el-timeline reverse slot="reference">
            <el-timeline-item v-for="item in notices" :key="item.id" :timestamp="item.time">
              <el-popover
                placement="bottom"
                width="300"
                trigger="hover"
                :content="item.content">
                <span slot="reference">{{ item.title }}</span>
              </el-popover>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
      <div class="card" ref="pieChart" style="width: 50%; height: 400px"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

// 配置生成函数（避免对象引用污染）
const getBasePieOptions = () => ({
  title: {
    text: '',
    subtext: '',
    left: 'center'
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)' // 添加格式化显示百分比
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    data: [] // 动态填充
  },
  series: [
    {
      name: '',
      type: 'pie',
      radius: ['40%', '70%'], // 环形效果
      avoidLabelOverlap: true,
      label: {
        show: true,
        position: 'inside',
        formatter: '{d}%'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '16',
          fontWeight: 'bold'
        }
      },
      data: []
    }
  ]
});

export default {
  name: 'Home',
  data() {
    return {
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      notices: [],
      chartInstance: null // 图表实例引用
    }
  },
  mounted() { // 确保DOM已挂载
    this.fetchData();
    this.$nextTick(() => { // 确保DOM更新完成
      this.initChart();
    });
  },
  beforeDestroy() { // 组件销毁前清理
    if (this.chartInstance) {
      this.chartInstance.dispose();
      this.chartInstance = null;
    }
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    fetchData() {
      // 并行请求
      Promise.all([
        this.$request.get('/notice/selectAll'),
        this.$request.get('/contest/getPie')
      ]).then(([noticesRes, pieRes]) => {
        // 处理通知数据
        if (noticesRes.code === '200') {
          this.notices = noticesRes.data || [];
        }

        // 处理饼图数据
        if (pieRes.code === '200') {
          this.updateChart(pieRes.data);
        }
      }).catch(error => {
        console.error('数据请求失败:', error);
        this.$message.error('数据加载失败');
      });
    },

    initChart() {
      if (!this.$refs.pieChart) return;

      // 销毁旧实例
      if (this.chartInstance) {
        this.chartInstance.dispose();
      }

      // 初始化新实例
      this.chartInstance = echarts.init(this.$refs.pieChart);
      window.addEventListener('resize', this.handleResize);
    },

    updateChart(pieData) {
      if (!this.chartInstance) return;

      // 生成新配置
      const options = getBasePieOptions();
      options.title.text = pieData.text;
      options.title.subtext = pieData.subtext;
      options.legend.data = pieData.data.map(item => item.name); // 动态生成图例
      options.series[0].name = pieData.name;
      options.series[0].data = pieData.data;

      // 应用配置
      this.chartInstance.setOption(options, true); // 第二个参数true表示清空后重新设置

      // 默认显示加载动画
      this.chartInstance.showLoading('default', {
        text: '加载中',
        color: '#409eff',
        textColor: '#333',
        maskColor: 'rgba(255, 255, 255, 0.8)'
      });

      // 模拟数据加载完成（实际应根据请求状态调整）
      setTimeout(() => {
        this.chartInstance.hideLoading();
      }, 500);
    },

    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    }
  }
}
</script>

<style scoped>
.card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-left: 10px;
}
</style>